package net.sxnic.normal.security.action;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import net.sxnic.comm.CommActionSupport;
import net.sxnic.comm.utils.CommUtils;
import net.sxnic.comm.utils.PropertyUtil;
import net.sxnic.item.ucenter.UcenterService;
import net.sxnic.normal.util.Constants;
import net.sxnic.ugr.UgrConstant;
import net.sxnic.ugr.context.AppContext;
import net.sxnic.ugr.permission.Permission;
import net.sxnic.ugr.role.Role;
import net.sxnic.ugr.user.User;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 系统登陆验证
 * 
 * @author yfsun
 *
 */
@Controller
public class Login extends CommActionSupport{

	private static Logger logger = LoggerFactory.getLogger(Login.class);
	
	private static final String INPUT="login";

	@Autowired
	private UcenterService ucenterService;

	@RequestMapping(value = "/login.jspa", method = RequestMethod.POST)
	public String submit(String username, String password, String verifyCode, ModelMap model) {
		
		try {
			// 是否有验证码
//			if (Boolean.valueOf(PropertyUtil.getProperty("login.verify"))) {
//				if (StringUtils.isBlank(verifyCode)) {
//					// addActionError("认证码不能为空！");					
//					return INPUT;
//				}
//				String rand = (String) request.getSession().getAttribute(
//						Constants.RAND);
//				if (!rand.equals(verifyCode)) {
//					// addActionError("认证码不正确");
//					return INPUT;
//				}
//			}

			if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
				// addActionError("用户名或密码错误！");
				model.addAttribute("actError", "用户名或密码错误！");
				return INPUT;
			}

			User user = ucenterService.findUserByUserName(username);

			// 如果用户不存在
			if (user == null) {
				// addActionError("用户名或密码错误！");
				return INPUT;
			}

			if (!user.getEnabled()) {
				// addActionError("用户名已被停用！");
				return INPUT;
			}

			// 如果密码不匹配
			if (!DigestUtils.md5Hex(password).equals(user.getPassword())) {
				// addActionError("用户名或密码错误！");
				return INPUT;
			}

			// bondip
			if (StringUtils.isNotBlank(user.getBoundIp())) {
				if (!user.getBoundIp().equals(CommUtils.findIP(request))) {
					logger.debug("====用户登陆使用非绑定IP：" + CommUtils.findIP(request));
				}
			}

			// roles
			String roles = "";
			Set<String> permissions = new HashSet<String>();
			for (Role r : user.getRoles()) {
				roles = r.getRole() + "," + roles;

				for (Permission p : r.getPermissions()) {
					if (!permissions.contains(p.getUrl())) {
						permissions.add(p.getUrl());
						logger.debug("==permissions=" + p.getUrl());
					}
				}
			}

			// 设置session
			// AppContext.setRoles(StringUtils.removeEnd(roles, ","));
			AppContext.setUserName(request, username);
			AppContext.setFullName(request, user.getFullname());
			// AppContext.setPermissions(permissions);
			 if(ucenterService.isUserInRole(user, "admin","subsite_admin")){
			 AppContext.setCssStyle(request,"vistaBlue");
			 }else{
			 AppContext.setCssStyle(request,"sky");
			 }

			// 设置user的最后登录时间
			user.setLastLoginDate(new Date());
			user.setLastLoginIp(CommUtils.findIP(request));
			ucenterService.updateUser(user);

			// 从在线用户列表中添加
			UgrConstant.LOGIN_USER_MAP.put(user.getUsername(), new Date());

			// log
			logger.debug("===" + username + "===login===success===");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:/main.jspa";
	}
}
